/**
 * 
 */
package com.hcmu.view.MainHome;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import vanhoc.android.utils.ResourceUtils;
import vanhoc.android.utils.Utils;

import com.telpoo.truyencuoi.R;
import com.hcmu.common.Logger;
import com.hcmu.common.SharePreferencesHelper;
import com.hcmu.common.SpinnerSetting;
import com.hcmu.menu.MenuActivity;
import com.hcmu.model.StoryDetailModel;
import com.hcmu.view.common.SettingFontSize;
import com.korovyansk.android.slideout.SlideoutActivity;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;
import com.markupartist.android.widget.ActionBar.Action;
import com.markupartist.android.widget.ActionBar.IntentAction;
import com.markupartist.android.widget.ActionItem;
import com.markupartist.android.widget.QuickAction;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Typeface;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author SEVEN
 *
 */
public class ViewStoryDetailOffline extends Activity {
	View app;
	static ActionBar actionBar;
	int story_id;
	static StoryDetailModel detailModel;
	TextView txtStoryContent;
	Handler handle = new Handler();
	List<Integer> listIds;
	ImageButton btnNext, btnPrevious, btnMore, btnFavourite;
	static Action favouriteAction, unfavouriteAction;
	Boolean isFavourite;
	ResourceUtils resUtils;
	QuickAction quickAction;
	Boolean isFavouriteList = false; //De biet xem co lay ve danh sach ListIds cua nhung truyn uu thich khong
	int currPosition; // vi tri cua truyen co id la story_id trong listIds
	private static final int ID_LIKE     	= 2;
	private static final int ID_SHARE   	= 3;
	private static final int ID_FAVOURITE 	= 5;
	private static final int ID_DELETE  = 4;	
	private static final int ID_INFO   		= 1;
	SettingFontSize settingFont;
	Boolean isShowTaskBar = true;
	LinearLayout innerContent,taskBarLayout;
	//bien luu tung do cua diem thu nhat, thu hai khi user vuot man hinh de chuyen truyen
	int xFirstPosition , xSecondPosition;
	ScrollView scrollView;
	
	
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		LayoutInflater lf = LayoutInflater.from(this);
		app = lf.inflate(R.layout.layout_detail_story_offline,  null);
		setContentView(app);
		
		Utils.setupAds(ViewStoryDetailOffline.this, ((ViewGroup)findViewById(R.id.rootAdView)));
		
		detailModel = new StoryDetailModel(this);
		resUtils = new ResourceUtils(this);
		
		//lay ve id cua truyen can xem dua vao intent
		story_id = getIntent().getExtras().getInt("ID");
		
		//lay ve danh sach id cua cac truyen cung nam trong 1 type voi truyen hien tai 
        listIds = getCurrentListIds();
        
        SharedPreferences sp = getPreferences(MODE_PRIVATE);
    	settingFont = new SettingFontSize(this, sp);
    	
		bindComponents();
		
		initActionMenu();
		 
		setActionBarTitle(); //title
		viewStoryContent(); // content
		setFavouriteButton();
		
		
		final Action newAction = new LikeAction(this, story_id , R.drawable.like_icon);
        actionBar.addAction(newAction);
        
        //update so lan doc
        updateNumberRead();
        
		final View[] children = new View[] { app };
	}
	
	
	/**
	 * Lay ve list id cua tat ca cac truyen nam trong cung 1 category hoac cung trong ds uu thich
	 * @return
	 */
	private List<Integer> getCurrentListIds() {
		isFavouriteList = getIntent().getBooleanExtra("isFavourite",false);
		if (isFavouriteList) 
			return detailModel.getFavouriteStoryIds();
		else
			return  detailModel.getStoryIds(story_id);
	}


	//show story content
	private void viewStoryContent() {
		txtStoryContent.setText(Html.fromHtml(detailModel.getStoryContent(story_id)));
		txtStoryContent.setTextSize(settingFont.getTextSize());
//		Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Arial.otf");
//		txtStoryContent.setTypeface(tf);
	}



	private void updateNumberRead() {
		 detailModel.updateNumRead(story_id);
	}

	private void setActionBarTitle() {
		//get title
		String story_title = detailModel.getStoryTitle(story_id);
        actionBar.setTitle(story_title);
	}

	
	private void setFavouriteButton(){
		//btnFavourite.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		if (detailModel.isFavourite(story_id)) {
			btnFavourite.setImageResource(R.drawable.favourite_icon);
		}else{
			btnFavourite.setImageResource(R.drawable.unfavourite_icon);
		}
	}
	

	private void bindComponents() {
		actionBar 			= (ActionBar) app.findViewById(R.id.actionbar);
		txtStoryContent 	= (TextView) app.findViewById(R.id.txtContent);
		btnNext 			= (ImageButton) app.findViewById(R.id.btnNext);
		btnPrevious 		= (ImageButton) app.findViewById(R.id.btnPrevious);
		btnMore 			= (ImageButton) app.findViewById(R.id.btnMore);
		btnFavourite 		= (ImageButton) app.findViewById(R.id.btnFavourite);
		innerContent 		= (LinearLayout) app.findViewById(R.id.innerContent);
		taskBarLayout 		= (LinearLayout) app.findViewById(R.id.taskBarLayout);
		taskBarView();
		scrollView = (ScrollView) app.findViewById(R.id.scrollView);
		
		
		setNextButton();
		setPreviousButton();
		setFavouriteButton();
		
		
		btnNext.setOnClickListener(nextEventListener);
		btnPrevious.setOnClickListener(previousEventListener);
		
		btnMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				quickAction.show(v);
			}
		});
		
		
		btnFavourite.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//update favourite state
				if (detailModel.isFavourite(story_id)) {
					detailModel.updateFavourite(story_id, false);
					Toast.makeText(getApplicationContext(), resUtils.getString(R.string.REMOVE_STORY_TO_FAVOURITE_LIST), Toast.LENGTH_LONG).show();
				}else{
					detailModel.updateFavourite(story_id, true);
					Toast.makeText(getApplicationContext(), resUtils.getString(R.string.ADD_STORY_TO_FAVOURITE_LIST), Toast.LENGTH_LONG).show();
				}
				setFavouriteButton();
			}
		});
		
		
		
		innerContent.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isShowTaskBar) {
					isShowTaskBar = false;
				}else {
					isShowTaskBar = true;
				}
				taskBarView();
			}
		});
		
		
		/*innerContent.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				DisplayMetrics display = new DisplayMetrics();
				getWindowManager().getDefaultDisplay().getMetrics(display);
				//Lay ve kich thuoc cua man hinh
				int screenWidth = display.widthPixels;
				int screentHeight = display.heightPixels;
				//tung do cua tam diem cua man hinh
				int xCenter = screenWidth/2;
				int minSpace = 100;
				
				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						xFirstPosition = (int) event.getX();
					case MotionEvent.ACTION_UP:
						xSecondPosition	=	(int) event.getX();
				}
				
				int space = Math.abs(xSecondPosition - xFirstPosition);
				if (space >= minSpace) {
					if (xSecondPosition > xCenter && xCenter > xFirstPosition) {
						previous();
					}
					if (xSecondPosition < xCenter && xCenter < xFirstPosition) {
						next();
					}
				}
				
				return true;
			}
		});*/
	}
	
	
	private void taskBarView() {
		// TODO Auto-generated method stub
		if (isShowTaskBar) {
			taskBarLayout.setVisibility(View.VISIBLE);
		}else{
			taskBarLayout.setVisibility(View.GONE);
		}
	}
	
	private void setNextButton(){
		if (getSizeListIds()==1 || (story_id == listIds.get(getSizeListIds()-1))) {
			btnNext.setImageResource(R.drawable.ic_next_disable);
			btnNext.setOnClickListener(null);
		}else{
			btnNext.setImageResource(R.drawable.ic_next);
			btnNext.setOnClickListener(nextEventListener);
		}
	}
	
	private void setPreviousButton(){
		if (getSizeListIds()==1 || (story_id == listIds.get(0))) {
			btnPrevious.setImageResource(R.drawable.ic_previous_disable);
			btnPrevious.setOnClickListener(null);
		}else{
			btnPrevious.setImageResource(R.drawable.ic_previous);
			btnPrevious.setOnClickListener(previousEventListener);
		}
	}
	

	
	private void initActionMenu() {
		ActionItem infoAction 	= new ActionItem(ID_INFO, resUtils.getString(R.string.INFO),resUtils.getBackgroundIcon(R.drawable.menu_info));
		ActionItem likeAction 	= new ActionItem(ID_LIKE, resUtils.getString(R.string.LIKE), resUtils.getBackgroundIcon(R.drawable.like_32_icon));
        ActionItem shareAction 	= new ActionItem(ID_SHARE, resUtils.getString(R.string.SHARE), resUtils.getBackgroundIcon(R.drawable.share_icon));
        ActionItem favouriteAction 	= new ActionItem(ID_FAVOURITE, resUtils.getString(R.string.FAVOURITE_LIST), resUtils.getBackgroundIcon(R.drawable.yellow_star_icon));
        ActionItem deleteAction 	= new ActionItem(ID_DELETE, resUtils.getString(R.string.DELETE), resUtils.getBackgroundIcon(R.drawable.delete_32_icon));
        
        //use setSticky(true) to disable QuickAction dialog being dismissed after an item is clicked
        //infoAction.setSticky(true);
        //likeAction.setSticky(true);
        
      //create QuickAction. Use QuickAction.VERTICAL or QuickAction.HORIZONTAL param to define layout 
        //orientation
		quickAction = new QuickAction(this, QuickAction.VERTICAL);
		
		//add action items into QuickAction
        quickAction.addActionItem(infoAction);
		quickAction.addActionItem(likeAction);
        quickAction.addActionItem(shareAction);
        quickAction.addActionItem(deleteAction);
        quickAction.addActionItem(favouriteAction);
        
        
      //Set listener for action item clicked
		quickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {			
			@Override
			public void onItemClick(QuickAction source, int pos, int actionId) {				
				ActionItem actionItem = quickAction.getActionItem(pos);
				//here we can filter which action item was clicked with pos or actionId parameter
				switch (actionId) {
					case ID_LIKE:
						detailModel.updateNumLike(story_id);
			        	Toast.makeText(ViewStoryDetailOffline.this,resUtils.getString(R.string.LIKED), Toast.LENGTH_LONG).show();
						break;
					case ID_SHARE:
			        	//Toast.makeText(ViewStoryDetailOffline.this,resUtils.getString(R.string.LIKED), Toast.LENGTH_LONG).show();
						
						/*Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
				        shareIntent.setType("text/plain");
				        shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
				        PackageManager pm = getPackageManager();
				        activityList = pm.queryIntentActivities(shareIntent, 0); 
				        */
						
						Intent intent = new Intent(Intent.ACTION_SEND);
						intent.setType("text/plain");
						intent.putExtra(Intent.EXTRA_TEXT, detailModel.getStoryTitle(story_id) + "\n" + detailModel.getStoryContent(story_id));
						startActivity(Intent.createChooser(intent, "Share with"));
							
						//shareViaFacebook();
						break;
					case ID_INFO:
						showStoryInfo();
						break;
					case ID_FAVOURITE:
						startActivity(new Intent(ViewStoryDetailOffline.this, FavouriteList.class));
						break;
					case ID_DELETE:
						deleteStory();
						break;
					default:
						break;
				}
			}
		});
		
		
		
		//set listnener for on dismiss event, this listener will be called only if QuickAction dialog was dismissed
		//by clicking the area outside the dialog.
		quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {			
			@Override
			public void onDismiss() {
				//Toast.makeText(getApplicationContext(), "Dismissed", Toast.LENGTH_SHORT).show();
			}
		});
      		
	}
	
	
	private void shareViaFacebook() {
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		shareIntent.setType("text/plain");
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
		PackageManager pm = this.getPackageManager();
		List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
		for (final ResolveInfo app : activityList) {
		    if ((app.activityInfo.name).contains("facebook")) {
		        final ActivityInfo activity = app.activityInfo;
		        final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
		        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		        shareIntent.setComponent(name);
		        startActivity(shareIntent);
		        break;
		   }
		}
	}
	
	/**
	 * Display detail info of the story 
	 */
	protected void showStoryInfo() {
		final Dialog storyDetaiDialog = new Dialog(this);
		storyDetaiDialog.setContentView(R.layout.layout_dialog_story_info);
		storyDetaiDialog.setTitle(resUtils.getString(R.string.DETAIL));
		
		HashMap<String, String> storyInfo = detailModel.getStoryInfo(story_id);
		
		//get textboxs
		TextView txtTitle = (TextView) storyDetaiDialog.findViewById(R.id.txtTitle);
		TextView txtCategory = (TextView) storyDetaiDialog.findViewById(R.id.txtCategory);
		TextView txtNumRead = (TextView) storyDetaiDialog.findViewById(R.id.txtNumRead);
		TextView txtNumLike = (TextView) storyDetaiDialog.findViewById(R.id.txtNumLike);
		TextView txtNumShare = (TextView) storyDetaiDialog.findViewById(R.id.txtNumShare);
		
		
		txtTitle.setText(storyInfo.get("TITLE"));
		txtCategory.setText(storyInfo.get("CATEGORY"));
		txtNumRead.setText(storyInfo.get("NUMREAD"));
		txtNumLike.setText(storyInfo.get("NUMLIKE"));
		txtNumShare.setText(storyInfo.get("NUMSHARE"));
		
		
		Button btnClose = (Button) storyDetaiDialog.findViewById(R.id.btnCloseHelp);
		btnClose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				storyDetaiDialog.dismiss();
			}
		});
		//show
		storyDetaiDialog.show();
	}


	protected void deleteStory() {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle(resUtils.getString(R.string.CONFIRM_DELETE_STORY));
		
		alertDialog.setButton(resUtils.getString(R.string.OK), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (detailModel.deleteStory(story_id)) {
					startActivity(new Intent(ViewStoryDetailOffline.this, OfflineMainView.class));
					Toast.makeText(ViewStoryDetailOffline.this,resUtils.getString(R.string.SUCCESSFULLY), Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(ViewStoryDetailOffline.this,resUtils.getString(R.string.UNSUCCESSFULLY), Toast.LENGTH_LONG).show();
				}
			}
		});
		
		alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		alertDialog.show();
	}


	private OnClickListener OpenFeatureEventLitener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			quickAction.show(v);
		}
	};
	
	
	private OnClickListener nextEventListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			//Neu truyen dang doc nam o cuoi danh sach thi dung. Neu khong nam o cuoi thi chuyen sang truyen tiep theo
			next();
		}
	};
	
	
	
	private int getSizeListIds(){
		return listIds.size();
	}
	
	private void next(){
		if (story_id != listIds.get(getSizeListIds()-1)) { //ptu cuoi cung
			story_id = listIds.get(getLocalPosition(story_id)+1);
			setActionBarTitle(); //title
			viewStoryContent(); // content
		}
		setNextButton();
		setPreviousButton();
		setFavouriteButton();
	}
	
	
	private void previous(){
		if (story_id != listIds.get(0)) { //ptu dau tien
			story_id = listIds.get(getLocalPosition(story_id)-1);
			setActionBarTitle(); //title
			viewStoryContent(); // content
		}
		
		setNextButton();
		setPreviousButton();
		setFavouriteButton();
	}
	
	
	private OnClickListener previousEventListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			previous();
		}
	};
	
	//Lay ve vi tri cua story_id trong listIds
	private int getLocalPosition(int id) {
		for (int i = 0; i < getSizeListIds(); i++) {
			if (listIds.get(i) == id) {
				return i;
			}
		}
		return -1;
	}
		
	
	/**
	 * Update number like khi user click vao like icon
	 * @author SEVEN
	 *
	 */
	public static class LikeAction extends AbstractAction {
        private Context mContext;
        private int storyID;
        
        public LikeAction(Context context, int storyId,int drawable) {
            super(drawable);
            storyID = storyId;
            mContext = context;
        }

        @Override
        public void performAction(View view) {
        	//update num like
        	detailModel.updateNumLike(storyID);
        }
    }
	
	

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_offline_detail, menu);
        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			settingFont.show(txtStoryContent);
			return false;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		/*if (!detailModel.isFavourite(story_id)) {
			startActivity(new Intent(this, OfflineMainView.class));
		}*/
	}
}